//
//  TJAccountViewModel.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/11.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

// 用来管理TJAccountModel的业务逻辑:网络请求 / 数据归档,解挡 / 字典转模型.
class TJAccountViewModel: NSObject {

    // 单例.
    static let shareUserAccount:TJAccountViewModel = TJAccountViewModel()
    
    // 私有化单例的init方法,让外界只能用share...来获取单例.
    private override init() {
        super.init()
        // 加载用户账号信息.对于单例,此处只会执行一次.
        userAccount = loadUserAcount()
    }
    
    // 让model成为ViewModel的属性.---->当外界可以通过ViewModel来拿到model.(model不直接暴露给外界,外界只访问ViewModel).
    var userAccount:TJUserAcount?
    
    // 记录用户是否登录.
    var isUserAccountLogin : Bool {
    
        get {
            // 当用户点击登录,授权之后,服务器返回字典,我们在KVC转模型的时候已经给account赋值,并保存沙盒了.当用户退出程序,在即启动,创建ViewModel单例时,会从沙盒加载已经保存的account,此时就有值了.
            return userAccount != nil
        }
    }
    
   
    
    // MARK: 获取access tocken方法.
    func loadAccessTocken (code:String,loadAccessTokenCallBack:(error:NSError?)->()) {
        
        // 1,URL.(新浪提供的)
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2,请求参数.
        let prameters:[String:String] = [
            
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 3.发送请求.
        // 有progress的没有过时.
        TJNetWorkManager.shareNetWorkManager.POST(urlString, parameters: prameters, progress: nil, success: { (_, responseObject) -> Void in
            // TJPrint("请求成功:result= \(responseObject)")
            // 将返回结果转为字典.
            let result = responseObject as? [String:AnyObject]
            if let dict = result {
                
                // 进行字典转模型.
                 self.userAccount = TJUserAcount(dict: dict)
                 TJPrint("字典转模型成功\(self.userAccount)")
                
                // 归档数据.
                self.saveUserAccount()
                
                // 加载token成功回调.
                loadAccessTokenCallBack(error: nil)
            }
            
            }) { (_, error) -> Void in
                TJPrint(error)
                // 失败回调.
                loadAccessTokenCallBack(error: error)
        }
    }
    
    
    // MARK :  请求用户头像和昵称.
    func loadUserInfo(loadUserInfoCallBack:(error:NSError?)->()) {
    
        // 1,URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 2,参数.
        // 守卫access_token.
//        userAccount?.access_token = nil
        guard let access_token = userAccount?.access_token else{
            
            let error = TJNetWorkError.AcceseTokenEmpty.NetWorkError()
            loadUserInfoCallBack(error: error)
            return
        }
        // 守卫uid.--> "此处也可以不用守卫,因为该参数不是请求的必须参数"
//        userAccount?.uid = nil
        guard let uid = userAccount?.uid else{
            
            let error = TJNetWorkError.UidEmpty.NetWorkError()
            loadUserInfoCallBack(error: error)
            return
        }
        
        let prameters:[String:String] = [
        
            "access_token":access_token,
            "uid":uid
        ]
        
        // 3,请求.
        TJNetWorkManager.shareNetWorkManager.GET(urlString, parameters: prameters, progress: nil, success: { (task, responseObject) -> Void in
            
//            TJPrint("请求用户信息成功:\(responseObject)")
            // 给模型属性赋值.
            if let dict = responseObject as? [String:AnyObject] {
            
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                // 保存到沙盒.
                self.saveUserAccount()
                // 成功回调.
                loadUserInfoCallBack(error: nil)
            }
            
            
            }) { (task, error) -> Void in
                TJPrint("请求用户信息失败:\(error)")
                // 失败回调.
                loadUserInfoCallBack(error: error)
        }
        
    }
    
    // MARK: 归档用户账号信息.
    private func saveUserAccount() {
    
        if userAccount == self.userAccount {
//        TJPrint(accountPath)
            // 归档模型数据.
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    // MARK: 解挡用户账号信息.
    private func loadUserAcount()->TJUserAcount? {
        
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? TJUserAcount
        
        // 判断是否可以解挡出有效账号:不为空,且没过期.
//        account?.dueDate = NSDate.init(timeIntervalSinceNow: -100)
        if account != nil && account?.dueDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // 账号不为空,且没过期.
            return account
        }
        
        // 没有加载到有效账号.
        return nil
    }
    
    
    
    
}
